<template>
  <div class="yt-page">
    <img class="form-bg" :style="`height: ${clientHeight}`" :src="require('./bg.jpg')">
    <yt-form class="form" :rules="rules" :model="user">
      <div class="form-box">
        <yt-input class="form-input" v-model="user.username" type="text" placeholder="请输入账号" fillColor="transparent" theme="light" align="left" border />
      </div>
      <div class="form-box">
        <yt-input class="form-input" v-model="user.password" type="password" placeholder="请输入密码" fillColor="transparent" theme="light" align="left" border />
      </div>
      <yt-checkBox v-model="rememberPassword" name="记住密码">
        <span style="color: white; font-size: 12px">记住密码</span>
      </yt-checkBox>
      <yt-btn class="form-btn" style="background-color: #35ca98;" validator :loading="doLogin">
        登录
      </yt-btn>
    </yt-form>
  </div>
</template>

<script>
import { GetStore, SetStore, Store, EVENTS, BUS } from '@/store'
import { commonApi } from '@/common/api/commonApi.js'

export default {
  name: 'page-login',

  data() {
    return {
      rememberPassword: ['记住密码'],
      user: {
        username: GetStore(Store.user) ? GetStore(Store.user).username : '',
        password: localStorage.getItem('password')
          ? localStorage.getItem('password')
          : ''
      },
      rules: {
        username: {
          type: 'string',
          required: true,
          message: '用户名不能为空!'
        },
        password: { type: 'string', required: true, message: '密码不能为空!' }
      },
      clientHeight: '600px'
    }
  },
  mounted() {
    // 动态设置背景高度，即使键盘上去元素高度还是不会改变
    this.clientHeight = `${document.documentElement.clientHeight}px`
  },
  methods: {
    async doLogin(loaded) {
      try {
        await commonApi.login(this.user)
        let {
          user,
          roles,
          enterprise,
          organization
        } = await commonApi.runCloud('getUserInfo')

        // 这里单独使用 localStorage存储，与全局方法 SetStore 方式不统一
        if (this.rememberPassword.length) {
          localStorage.setItem('password', this.user.password)
        } else {
          localStorage.getItem('password')
            ? localStorage.removeItem('password')
            : null
        }

        SetStore(Store.user, user)
        SetStore(Store.roles, roles)
        SetStore(Store.enterprise, enterprise)
        SetStore(
          Store.organization,
          organization
            ? { id: organization.id, ...organization.attributes }
            : null
        )
        this.$Toast('登录成功!')
        this.$router.$push('/home')
      } catch (e) {
        this.$Toast('密码错误!', 'error')
      }
      loaded()
    }
  }
}
</script>

<style scoped lang="stylus">
.form
  padding 240px 40px 0
  height auto

  &-bg
    position absolute
    z-index -1
    top 0
    left 0
    width 100%

  &-btn
    line-height 1.2em
    margin-top 30px

  &-box
    margin 0 10px

  &-input
    margin 15px 0
    height 36px
</style>
